package com.example.yls.demoa;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyService extends Service {
    private boolean isLive = true;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("MyService","thread id = " + Thread.currentThread().getId());

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLive){
                    Intent intent = new Intent();
                    intent.setAction("TIME_CHANGE");
                    intent.putExtra("time",getTimeStr());
                    intent.putExtra("str",changeStr("I Love Android"));
                    sendBroadcast(intent);

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public String changeStr(String str) {
        String s[] = str.split(" ");
        String ss = "";
        for (int i = 0; i<s.length;i++){
            ss+=changePlace(s[i]+" ");
        }
        return ss;
    }

    private String changePlace(String s) {
        char[] c= s.toCharArray();
        for (int i=0;i<c.length/2;i++){
            char ch = c[i];
            c[i]= c[c.length-i-1];
            c[c.length-i-1]=ch;
        }
        return String.valueOf(c);
    }


    //获取当前时间的字符串
    public String getTimeStr() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(date);
    }


    @Override
    public void onDestroy() {
        isLive = false;
        super.onDestroy();
    }
}





































